﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class BakupData : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userName"] != null)
        {
            if (!IsPostBack)
            {
                BindRecord();
            }

        }
        else
        {
            Response.Redirect(GetUrlPath.GetUrl + "/Login.aspx");
        }

    }

    protected void btnBackup_Click(object sender, EventArgs e)
    {
        BackupData();
              
    }

    //绑定数据库备份记录
    protected void BindRecord()
    {
        dgDataBakRecord.DataSource = DataBackup.ReadBackupRecord();
        dgDataBakRecord.Columns[0].Visible = false;
        dgDataBakRecord.DataBind();
    }

    protected void dgDataBakRecord_ItemCommand(object source, DataGridCommandEventArgs e)
    {
        lblmsg.Text = "";
        DataBackup bak = new DataBackup();
        //如果用户点击的是删除按钮
        if (e.CommandName == "delBackup")
        {
            if (dgDataBakRecord.Items.Count == 1)
            {
                if (dgDataBakRecord.CurrentPageIndex != 0)
                {

                    dgDataBakRecord.CurrentPageIndex = dgDataBakRecord.CurrentPageIndex - 1;
                }

            }

            //string  msgID =Convert.ToInt32( e.Item.Cells[0].Text);
            string fileName = Convert.ToString(e.Item.Cells[1].Text);
            string strPath = Server.MapPath("~\\files\\backup\\") + fileName;
            if (bak.DeleteBackupFile(fileName, strPath))
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('删除成功！');", true);
                BindRecord();

            }
            else
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('尝试删除时，出现未知错误,删除失败！请您联系管理员。');", true);
            }

        }
        //如果用户点击的是恢复按钮
        if (e.CommandName == "restore")
        {
            string dbName = Convert.ToString(e.Item.Cells[1].Text);
            string strPath = Server.MapPath("~\\files\\backup\\") + dbName;
            if (bak.Restore(strPath))
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('恢复成功！');", true);
            }
            else
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('尝试恢复数据库时，出现未知错误，很可能是因为其他用户正在使用该系统，或者是存在没有及时释放的数据库连接，造成恢复失败！建议您选择一个系统空闲时间进行恢复');", true);

            }

        }

    }

    protected void dgDataBakRecord_ItemCreated(object sender, DataGridItemEventArgs e)
    {

        foreach (DataGridItem dg in dgDataBakRecord.Items)
        {
            Label lb = (Label)dg.FindControl("lblLoad");
            string fileName = dg.Cells[1].Text;
            string encodeFilePath = Server.UrlEncode("/backup/" + fileName);
            lb.Text = "<a href='DownLoad.aspx?filepath=" + encodeFilePath + "'>点击下载</a>";
        }
        switch (e.Item.ItemType)
        {
            case ListItemType.EditItem:
            case ListItemType.AlternatingItem:
            case ListItemType.Item:

                Button btnDel = (Button)e.Item.FindControl("btnDelBackup");
                Button btnRestore = (Button)e.Item.FindControl("btnRestore");
                btnDel.Attributes.Add("onClick", "return confirm('您真的要删除这个备份吗？删除前，建议您将备份下载到本地保存！');");
                btnRestore.Attributes.Add("onClick", "return confirm('您真的要恢复这个备份吗？强烈建议您在恢复备份前使用“一键备份功能”备份当前的数据库！')");

                break;
        }
    }

    protected void dgDataBakRecord_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
    {
        dgDataBakRecord.CurrentPageIndex = e.NewPageIndex;
        BindRecord();
    }
    //备份数据库
    protected void   BackupData()
    {
        DataBackup bak = new DataBackup();
        DateTime  backTime = bak.BakTime;
        string dataBaseName = "XSSFSYSTEM" + string.Format("{0:yyyyMMddHHmm}", backTime) + ".bak";
        bak.BakName = dataBaseName;

        string Dirpath = Server.MapPath("~\\files\\backup\\");

        if (!Directory.Exists(Dirpath))
        {
            Directory.CreateDirectory(Dirpath);
        }
        string strPath = Dirpath + dataBaseName;

        //string strPath = Server.MapPath("~\\files\\backup\\") + dataBaseName;
        //首先判断是否已经存在同一分钟的备份
        if (!bak.CheckFileName(dataBaseName))
        {
            lblmsg.Text = "";
            if (bak.Backup("XSSFSYSTEM", strPath))
            {
                bak.GetDatabaseSize(Server.MapPath("~\\files\\backup\\") + dataBaseName);
                if (bak.InsertNewRecord())
                {
                    Response.Write("<script language='javascript'>alert('数据库备份成功！')</script>");
                    BindRecord();
    
                }
                else
                {
                    Response.Write("<script language='javascript'>alert('数据库已经备份成功，但是在尝试记录本次备份时，写入数据库失败！请您联系管理员。')</script>");
                }
            }
            else
            {
                Response.Write("<script language='javascript'>alert('由于未知原因，数据库备份失败！请联系管理员')</script>");
            }
        }
        else
        {
            lblmsg.Text = "<font color='red'>请不要频繁备份数据库！如需再次备份，请稍后片刻再备份数据库！</font>";
        }
    }
}
